<template>
  <div class="select">
    <Input @click="open" readonly :placeholder="placeholder">
      <template v-slot:suffix>dd</template>
    </Input>
    <teleport :to="to">
      <ul ref="options" class="select__options" v-if="isOpen">
        <li>
          <div>d</div>
          <div>d</div>
          <div>dsdasd</div>
        </li>
        <li>hello</li>
        <li>hello</li>
      </ul>
    </teleport>
  </div>
</template>

<script setup lang="ts">
import "./style.scss";
import { Input } from "../../input/index";
</script>

<script lang="ts">
import { defineComponent, ref } from "vue";
import { getDocumentScroll } from "../../../utils/index";
export default defineComponent({
  props: {
    to: {
      type: String,
      default: "body",
    },
    placeholder: String,
  },
  data() {
    return {
      isOpen: false,
    };
  },

  mounted() {
    document.addEventListener("click", (e) => {
      if (
        !this.$el.contains(e.target) &&
        this.$refs.options &&
        //@ts-ignore
        !this.$refs.options.contains(e.target)
      ) {
        this.close();
      }
    });
  },

  methods: {
    open() {
      if (this.isOpen) {
        return this.close();
      }
      this.isOpen = true;
      this.$nextTick(() => {
        this.updatePosition();
      });
    },
    close() {
      this.isOpen = false;
    },
    updatePosition() {
      const st = getDocumentScroll();
      const pos = this.$el.getBoundingClientRect();
      //@ts-ignore
      this.$refs.options.style.cssText = `
      left:${pos.left + st.left}px;
      top:${pos.bottom + st.top + 10}px;
      width:${pos.width}px`;
    },
  },
});
</script>
